package com.das.mechanic_base.adapter.main;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.das.mechanic_base.R;
import com.das.mechanic_base.app.X3AppRouterConstants;
import com.das.mechanic_base.app.X3RouterCenter;
import com.das.mechanic_base.bean.main.BottomShowBean;
import com.das.mechanic_base.bean.plan.PlanListBean;
import com.das.mechanic_base.utils.X3DateUtils;
import com.das.mechanic_base.utils.X3GlideNewUtils;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StringUtils;

import java.util.ArrayList;
import java.util.List;

public class X3HomeMiniAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<BottomShowBean> mList;

    private Context mContext;

    private PlanListBean listBean;

    private int workIndex;

    private SparseArray<Handler> handlerArray;

    private SparseArray<Runnable> runArray;

    /**
     * 0 正常
     * 1 空白占位
     */
    private int mEmptyType;

    public X3HomeMiniAdapter(Context mContext, int workIndex) {
        this.mContext = mContext;
        this.workIndex = workIndex;
        this.mList = new ArrayList<>();
        handlerArray = new SparseArray<>();
        runArray = new SparseArray<>();
        mEmptyType = 1;
    }

    public void changeQuickName(PlanListBean listBean) {
        this.listBean = listBean;
        notifyDataSetChanged();
    }

    public void changeTop(List<BottomShowBean> mList) {
        this.mList = mList;
        mEmptyType = X3StringUtils.isListEmpty(mList) ? 1 : 0;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        switch (viewType) {
            case 1:
                return new EmptyHolder(LayoutInflater.from(mContext).inflate(R.layout.x3_empty_home_item, parent, false));
            default:
                return new HomeMiniHolder(LayoutInflater.from(mContext).inflate(R.layout.x3_home_mini_layout, parent, false));
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        RecyclerView.LayoutParams vpLayout = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();
        if (position == mList.size() - 1) {
            vpLayout.topMargin = X3ScreenUtils.dipToPx(12,mContext);
            vpLayout.bottomMargin = X3ScreenUtils.dipToPx(20,mContext);
        }else {
            vpLayout.topMargin = X3ScreenUtils.dipToPx(12,mContext);
            vpLayout.bottomMargin = 0;
        }
        holder.itemView.setLayoutParams(vpLayout);

        if (getItemViewType(position) == 0) {

            HomeMiniHolder miniHolder = (HomeMiniHolder) holder;

            miniHolder.rl_create.setVisibility((position == mList.size() - 1) ? View.VISIBLE : View.GONE);
            miniHolder.rl_quick.setVisibility((position == mList.size() - 1) ? View.VISIBLE : View.GONE);

            if (listBean != null && !X3StringUtils.isEmpty(listBean.serviceBaseName)) {
                miniHolder.tv_quick.setText(listBean.serviceBaseName + "");
            }else {
                miniHolder.tv_quick.setText(mContext.getString(R.string.x3_quick_alone));
            }

            X3GlideNewUtils.loadNormalImage(mContext, X3StringUtils.getImageUrl(mList.get(position).getCarBrandImgUrl()),miniHolder.iv_icon,R.mipmap.x3_car_icon_no);

            String carBrand = X3StringUtils.isEmpty(mList.get(position).getCarBrandName()) ? "" : mList.get(position).getCarBrandName();
            String carStyle = X3StringUtils.isEmpty(mList.get(position).getCarStyleName()) ? "" : mList.get(position).getCarStyleName();
            String carNum = X3StringUtils.isEmpty(mList.get(position).getCarNum()) ? "" : "(" + mList.get(position).getCarNum() +")";
            boolean empty = X3StringUtils.isEmpty(carBrand) && X3StringUtils.isEmpty(carStyle);
            miniHolder.tv_car_brand.setText(empty ? mList.get(position).getCarNum() : carBrand + " " + carStyle + carNum);

            List<String> serviceNameList = mList.get(position).getServiceBaseNameList();

            String serviceName = "";
            if (!X3StringUtils.isListEmpty(serviceNameList)) {
                for (int i = 0; i < serviceNameList.size(); i++) {
                    if (i == 0) {
                        serviceName = serviceNameList.get(i);
                    }else {
                        serviceName = serviceName + ", " + serviceNameList.get(i);
                    }
                }
            }else {
                serviceName = "";
            }
            miniHolder.tv_service_name.setText(serviceName);

            long status = mList.get(position).getStatus();

            String nowTime = mList.get(position).getStartTime();

            int pkCurrentTime = X3DateUtils.isPkCurrentTime(nowTime);

            switch (pkCurrentTime) {
                case 0:
                    // 预约单
                    miniHolder.tv_time.setTextColor(Color.parseColor("#A5A5A5"));

                    if (miniHolder.mHandler != null) {
                        miniHolder.mHandler.removeCallbacks(miniHolder.runnable);
                    }

                    miniHolder.mHandler = new Handler();

                    miniHolder.runnable = new Runnable() {
                        @Override
                        public void run() {
                            String homeTimeCute = X3DateUtils.RelativeTime(nowTime,mContext);
                            if (X3DateUtils.isAfter) {
                                miniHolder.mHandler.removeCallbacks(this);
                            }else {
                                miniHolder.tv_time.setText(mContext.getString(R.string.x3_start_time) + ": " + homeTimeCute);
                                miniHolder.mHandler.postDelayed(this, 1000);
                            }
                        }
                    };

                    miniHolder.mHandler.post(miniHolder.runnable);

                    handlerArray.put(miniHolder.mHandler.hashCode(),miniHolder.mHandler);
                    runArray.put(miniHolder.runnable.hashCode(),miniHolder.runnable);

                    break;
                case 1:
                    if (iOnClickHomeWork != null) {
                        iOnClickHomeWork.iOnClickRefresh();
                    }
                    break;
                case 2:
                    miniHolder.tv_time.setTextColor(Color.parseColor("#F3465B"));

                    if (miniHolder.mHandler != null) {
                        miniHolder.mHandler.removeCallbacks(miniHolder.runnable);
                    }

                    miniHolder.mHandler = new Handler();

                    miniHolder.runnable = new Runnable() {
                        @Override
                        public void run() {
                            if (position < mList.size()) {
                                String homeTimeCute = X3DateUtils.getHomeTimeDelay(nowTime,mContext);
                                miniHolder.tv_time.setText(homeTimeCute);
                                miniHolder.mHandler.postDelayed(this, 1000);
                            }
                        }
                    };

                    miniHolder.mHandler.post(miniHolder.runnable);

                    handlerArray.put(miniHolder.mHandler.hashCode(),miniHolder.mHandler);
                    runArray.put(miniHolder.runnable.hashCode(),miniHolder.runnable);
                    break;
            }

            ((HomeMiniHolder) holder).iv_more.setOnClickListener(v -> {
                if (iOnClickHomeWork != null) {
                    iOnClickHomeWork.iOnClickShowDetail(mList.get(position),miniHolder.iv_more);
                }
            });

            //跳转到检测和施工
            holder.itemView.setOnClickListener(view -> {
                if (mList.get(position).isIfDetection()) {
                    //去检测报告
                    Bundle bundle = new Bundle();
                    bundle.putLong("id",mList.get(position).getId());
                    bundle.putLong("receiveBaseId",mList.get(position).getReceiveBaseId());
                    X3RouterCenter.startNavigate(X3AppRouterConstants.Router.MAIN_TAIN,bundle);
                    return;
                }
                //去保养，去施工
                Bundle bundle = new Bundle();
                bundle.putLong("id",mList.get(position).getId());
                bundle.putLong("carId",mList.get(position).getCarId());
                bundle.putLong("receiveBaseId",mList.get(position).getReceiveBaseId());
                X3RouterCenter.startNavigate(X3AppRouterConstants.Router.MAIN_SIVE,bundle);
            });

        }else {
            // 空白占位
            EmptyHolder emptyHolder = (EmptyHolder) holder;

            emptyHolder.tv_empty.setText(workIndex == 0 ? mContext.getString(R.string.not_have_today_order) : mContext.getString(R.string.not_have_order));

            emptyHolder.rl_create.setVisibility(View.VISIBLE);
            emptyHolder.rl_quick.setVisibility(View.VISIBLE);
            if (listBean != null && !X3StringUtils.isEmpty(listBean.serviceBaseName)) {
                emptyHolder.tv_quick.setText(listBean.serviceBaseName + "");
            }else {
                emptyHolder.tv_quick.setText(mContext.getString(R.string.x3_quick_alone));
            }
        }
    }

    @Override
    public int getItemViewType(int position) {
        return mEmptyType;
    }

    @Override
    public int getItemCount() {
        return X3StringUtils.isListEmpty(mList) ? 1 : mList.size();
    }

    class HomeMiniHolder extends RecyclerView.ViewHolder {
        ImageView iv_icon;
        TextView tv_car_brand;
        ImageView iv_more;
        TextView tv_service_name;
        TextView tv_time;
        RelativeLayout rl_create;
        RelativeLayout rl_quick;
        TextView tv_quick;
        private Handler mHandler;
        private Runnable runnable;
        public HomeMiniHolder(@NonNull View itemView) {
            super(itemView);
            iv_icon = itemView.findViewById(R.id.iv_icon);
            tv_car_brand = itemView.findViewById(R.id.tv_car_brand);
            iv_more = itemView.findViewById(R.id.iv_more);
            tv_service_name = itemView.findViewById(R.id.tv_service_name);
            tv_time = itemView.findViewById(R.id.tv_time);
            rl_create = itemView.findViewById(R.id.rl_create);
            rl_quick = itemView.findViewById(R.id.rl_quick);
            tv_quick = itemView.findViewById(R.id.tv_quick);

            rl_create.setOnClickListener(v -> {
                if (iOnClickHomeWork != null) {
                    iOnClickHomeWork.iCreateService();
                }
            });
            rl_quick.setOnClickListener(v -> {
                if (iOnClickHomeWork != null) {
                    iOnClickHomeWork.iCreateQuick();
                }
            });
        }
    }

    class EmptyHolder extends RecyclerView.ViewHolder {
        TextView tv_empty;
        RelativeLayout rl_create;
        RelativeLayout rl_quick;
        TextView tv_quick;

        public EmptyHolder(@NonNull View itemView) {
            super(itemView);
            tv_empty = itemView.findViewById(R.id.tv_empty);
            rl_create = itemView.findViewById(R.id.rl_create);
            rl_quick = itemView.findViewById(R.id.rl_quick);
            tv_quick = itemView.findViewById(R.id.tv_quick);

            rl_create.setOnClickListener(v -> {
                if (iOnClickHomeWork != null) {
                    iOnClickHomeWork.iCreateService();
                }
            });
            rl_quick.setOnClickListener(v -> {
                if (iOnClickHomeWork != null) {
                    iOnClickHomeWork.iCreateQuick();
                }
            });
        }
    }

    private IOnClickHomeWork iOnClickHomeWork;

    public X3HomeMiniAdapter setiOnClickHomeWork(IOnClickHomeWork iOnClickHomeWork) {
        this.iOnClickHomeWork = iOnClickHomeWork;
        return this;
    }

    public interface IOnClickHomeWork {

        /**
         * 创建接车单
         */
        void iCreateService();

        /**
         * 快速检测
         */
        void iCreateQuick();

        void iOnClickRefresh();

        void iOnClickShowDetail(BottomShowBean showBean,View view);
    }
}
